package com.ljfiction.book.activitys;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.google.gson.Gson;
import com.ljfiction.book.Baner.MyfensiBean;
import com.ljfiction.book.Dialog.IsOrNoDialog;
import com.ljfiction.book.Dialog.NoBackgLodDialog;
import com.ljfiction.book.MyView.DividerItemDecoration;
import com.ljfiction.book.R;
import com.ljfiction.book.http.HttpManager;
import com.ljfiction.book.http.UserManageBean;
import com.ljfiction.book.tools.ScreenUtils;
import com.ljfiction.book.tools.SettingManager;
import com.lzy.okhttputils.OkHttpUtils;
import com.lzy.okhttputils.callback.StringCallback;
import com.lzy.okhttputils.request.BaseRequest;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener;
import com.zhy.autolayout.utils.AutoUtils;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;
import okhttp3.Response;

public class OtherfensiActivity extends BaseActivity {

    @BindView(R.id.back_otherfensi)
    ImageView backOtherfensi;
    @BindView(R.id.recycler_otherfensi)
    RecyclerView recyclerOtherfensi;
    @BindView(R.id.nodata_otherfensi)
    LinearLayout nodataOtherfensi;
    @BindView(R.id.smarch_otherfensi)
    SmartRefreshLayout smarchOtherfensi;
    @BindView(R.id.toptext_otherfensi)
    TextView toptextOtherfensi;

    private BaseQuickAdapter madpter;
    private List<MyfensiBean.DataBean.ListBean> listData = new ArrayList<>();
    private int type = 0;//0是ta的粉丝，1是ta的关注
    private Intent intent;
    private IsOrNoDialog isOrNoDialog;
    private String folloeId;
    private NoBackgLodDialog noBackgLodDialog;
    private int page = 1;
    private boolean isfirst = true;
    private MyfensiBean myfensibean;
    private String userId;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_otherfensi);
        ButterKnife.bind(this);
        userId = getIntent().getStringExtra("userId");
        type = getIntent().getIntExtra("type", 0);
        if (type == 0) {
            toptextOtherfensi.setText("Ta的粉丝");
        } else {
            toptextOtherfensi.setText("Ta的关注");
        }
        intView();
        intData();
    }

    private void intView() {
        recyclerOtherfensi.setAdapter(madpter = new BaseQuickAdapter<MyfensiBean.DataBean.ListBean, BaseViewHolder>(R.layout.myfensiormyguanzhu_item, listData) {
            @Override
            protected void convert(BaseViewHolder helper, MyfensiBean.DataBean.ListBean item) {
                AutoUtils.autoSize(helper.itemView);
                Glide.with(mContext).load(item.getUserHeadPortraitURL()).override(ScreenUtils.getNum(mContext,52), ScreenUtils.getNum(mContext,52)).into((ImageView) helper.getView(R.id.image_myfensi));
                helper.setText(R.id.name_myfensi, item.getFollowUserName())
                        .setText(R.id.dengli_myfensi, "LV" + item.getUserGrade());
                if (item.getUserSex() == 0) {
                    ((ImageView) helper.getView(R.id.sex_myfensi)).setImageResource(R.mipmap.sex_n);
                } else {
                    ((ImageView) helper.getView(R.id.sex_myfensi)).setImageResource(R.mipmap.sex_v);
                }
                if (item.getVipGrade() > 0) {
                    helper.getView(R.id.huangguan_myfensi).setVisibility(View.VISIBLE);
                } else {
                    helper.getView(R.id.huangguan_myfensi).setVisibility(View.GONE);
                }
                if (item.getIsfollow() == 1) {
                    ((ImageView) helper.getView(R.id.isguanzhu)).setImageResource(R.mipmap.mygz);
                } else {
                    ((ImageView) helper.getView(R.id.isguanzhu)).setImageResource(R.mipmap.mynogz);
                }
                helper.addOnClickListener(R.id.toguanzhu);
                helper.addOnClickListener(R.id.image_myfensi);
            }

        });
        recyclerOtherfensi.setLayoutManager(new LinearLayoutManager(this));
        recyclerOtherfensi.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL_LIST));
        madpter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, final int position) {
                switch (view.getId()) {
                    case R.id.image_myfensi:
                        intent=new Intent(OtherfensiActivity.this,UserCenterActivity.class);
                        if (type == 0) {
                            intent.putExtra("userId", String.valueOf(listData.get(position).getUserId()));
                        } else {
                            intent.putExtra("userId", String.valueOf(listData.get(position).getFollowId()));
                        }

                        startActivity(intent);
                        break;
                    case R.id.toguanzhu:
                        if (!UserManageBean.isLogin(OtherfensiActivity.this)) {
                            return;
                        }
                        if (type == 1) {
                            isOrNoDialog = new IsOrNoDialog(OtherfensiActivity.this, "是否取消关注？", true);
                            isOrNoDialog.setListener(new IsOrNoDialog.Listener() {
                                @Override
                                public void okClick() {
                                    todeletguanzhu(position);
                                }

                                @Override
                                public void closeClick() {

                                }
                            });
                        } else if (listData.get(position).getIsfollow() == 1) {
                            isOrNoDialog = new IsOrNoDialog(OtherfensiActivity.this, "是否取消关注？", true);
                            isOrNoDialog.setListener(new IsOrNoDialog.Listener() {
                                @Override
                                public void okClick() {
                                    todeletguanzhu(position);
                                }

                                @Override
                                public void closeClick() {

                                }
                            });
                        } else {
                            isOrNoDialog = new IsOrNoDialog(OtherfensiActivity.this, "是否关注此人？", true);
                            isOrNoDialog.setListener(new IsOrNoDialog.Listener() {
                                @Override
                                public void okClick() {
                                    toAddGuanzhu(position);
                                }

                                @Override
                                public void closeClick() {

                                }
                            });
                        }
                        break;
                }
            }
        });
        smarchOtherfensi.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
            @Override
            public void onLoadMore(RefreshLayout refreshlayout) {
                if (myfensibean.getData().isIsLastPage()) {
                    smarchOtherfensi.finishLoadMore();
                    smarchOtherfensi.setEnableLoadMore(false);
                } else {
                    page++;
                    intData();
                }
            }

            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                page = 1;
                listData.clear();
                smarchOtherfensi.setEnableLoadMore(true);
                intData();
            }
        });
    }

    private void intData() {
        if (type == 0) {
            OkHttpUtils.get(HttpManager.IP + "/fans-userFans")

                    .params("puserid", userId)
                    .params("startpage", String.valueOf(page))
                    .execute(new StringCallback() {
                        @Override
                        public void onBefore(BaseRequest request) {
                            super.onBefore(request);
                            if (isfirst) {
                                if (noBackgLodDialog == null) {
                                    noBackgLodDialog = new NoBackgLodDialog(OtherfensiActivity.this, true);
                                }
                                noBackgLodDialog.show();
                            }
                        }

                        @Override
                        public void onSuccess(String s, Call call, Response response) {
                            if (isfirst) {
                                noBackgLodDialog.dismis();
                                isfirst = false;
                            }
                            smarchOtherfensi.finishLoadMore();
                            smarchOtherfensi.finishRefresh();
                            Gson g = new Gson();
                            myfensibean = g.fromJson(s, MyfensiBean.class);
                            try {
                                if (myfensibean.getReturnCode() == 200) {
                                    listData.addAll(myfensibean.getData().getList());
                                    madpter.notifyDataSetChanged();
                                    if (listData.size() < 1) {
                                        nodataOtherfensi.setVisibility(View.VISIBLE);
                                    } else {
                                        nodataOtherfensi.setVisibility(View.GONE);
                                    }
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                            }

                        }
                    });
        } else {
            OkHttpUtils.get(HttpManager.IP + "/fans-userFollow")

                    .params("puserid", userId)
                    .params("startpage", String.valueOf(page))
                    .execute(new StringCallback() {
                        @Override
                        public void onBefore(BaseRequest request) {
                            super.onBefore(request);
                            if (isfirst) {
                                if (noBackgLodDialog == null) {
                                    noBackgLodDialog = new NoBackgLodDialog(OtherfensiActivity.this, true);
                                }
                                noBackgLodDialog.show();
                            }
                        }

                        @Override
                        public void onSuccess(String s, Call call, Response response) {
                            if (isfirst) {
                                noBackgLodDialog.dismis();
                                isfirst = false;
                            }
                            smarchOtherfensi.finishLoadMore();
                            smarchOtherfensi.finishRefresh();
                            Gson g = new Gson();
                            myfensibean = g.fromJson(s, MyfensiBean.class);

                            try {
                                if (myfensibean.getReturnCode() == 200) {
                                    listData.addAll(myfensibean.getData().getList());
                                    for (MyfensiBean.DataBean.ListBean i :
                                            listData) {
                                        i.setIsfollow(1);
                                    }
                                    madpter.notifyDataSetChanged();
                                    if (listData.size() < 1) {
                                        nodataOtherfensi.setVisibility(View.VISIBLE);
                                    } else {
                                        nodataOtherfensi.setVisibility(View.GONE);
                                    }
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                            }

                        }
                    });
        }
    }

    private void toAddGuanzhu(final int position) {
        if (type == 0) {
            folloeId = String.valueOf(listData.get(position).getUserId());
        } else {
            folloeId = String.valueOf(listData.get(position).getFollowId());
        }
        OkHttpUtils.post(HttpManager.IP + "/fans-addFans")

                .params("followId", folloeId)
                .params("followUserName", listData.get(position).getFollowUserName())
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(String s, Call call, Response response) {
                        try {
                            JSONObject js = new JSONObject(s);
                            if (js.getInt("returnCode") == 200) {
                                listData.get(position).setIsfollow(1);
                                madpter.notifyDataSetChanged();

                            }else if (400 == js.getInt("returnCode") ) {
                                Intent intent=new Intent(OtherfensiActivity.this,LoginActivity.class);
                                startActivity(intent);
                            }
                            showToast(js.getString("msg"));
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                });
    }

    private void todeletguanzhu(final int position) {
        if (type == 0) {
            folloeId = String.valueOf(listData.get(position).getUserId());
        } else {
            folloeId = String.valueOf(listData.get(position).getFollowId());
        }
        OkHttpUtils.post(HttpManager.IP + "/fans-CancelFollow/")

                .params("followId", folloeId)
                .params("followUserName", listData.get(position).getFollowUserName())
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(String s, Call call, Response response) {
                        try {
                            JSONObject jso = new JSONObject(s);
                            if (jso.getInt("returnCode") == 200) {
                                if (type == 1) {
                                    listData.remove(position);
                                    madpter.notifyDataSetChanged();
                                } else {
                                    listData.get(position).setIsfollow(0);
                                    madpter.notifyDataSetChanged();
                                }
                            }
                            showToast(jso.getString("msg"));
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                });
    }

    @OnClick(R.id.back_otherfensi)
    public void onViewClicked() {
        goBack();
    }
}
